package com.jlhlyby.link;

import com.jlhlyby.util.Print;

import java.util.List;

/**
 * 合并有序链表
 */
public class MergeTwoLists {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);
        Print.printLink(l1);
        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);
        Print.printLink(l2);
        Print.printLink(mergeTwoLists(l1,l2));
//        Print.printLink(mergeTwoListsD(l1,l2));

    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode preHeader = new ListNode();
        ListNode prev = preHeader;
        while (l1 != null && l2 != null){
            if (l1.val > l2.val){
                prev.next = l2;
                l2 = l2.next;
            }else {
                prev.next = l1;
                l1 = l1.next;
            }
            prev = prev.next;
        }
        prev.next = l2 == null ? l1 : l2;
        return preHeader.next;
    }
    public static ListNode mergeTwoListsD(ListNode l1, ListNode l2) {
       if (l1 == null){
           return l2;
       }
       if (l2 == null){
           return l1;
       }
       if (l1.val > l2.val){
           l2.next = mergeTwoListsD(l1,l2.next);
           return l2;
       }else{
           l1.next = mergeTwoListsD(l1.next,l2);
           return l1;
       }
    }
}
